import { _decorator, Component, Node ,EventTarget } from 'cc';
const { ccclass, property } = _decorator;


const eventTarget = new EventTarget();
globalThis._eventTarget = eventTarget;

@ccclass('loginClient')
export class loginClient extends Component {
    private _ws : any = null;
    start() {
        this._init();
    }

    update(deltaTime: number) {
        
    }

    private _init() {
        globalThis._loginClientMgr = this;
        this._connectServer();
    }
    private _connectServer(){
        const ws = new WebSocket("ws://127.0.0.1:3000");
        this._ws = ws;
        ws.onopen = ()=>{
            console.log('连接登陆服务器成功');
        }
        ws.onmessage = (result)=>{
            console.log('服务端发来了数据:',result.data);
            let message = JSON.parse(result.data);
            let type = message.type;
            let data = message.data;

            //在这里处理服务端发来的消息
            this.responseServerMessage(type,data)
        }
        ws.onclose = ()=>{
            console.log('与登录服务器连接断开');
        }
        ws.onerror = (err)=>{
            console.log('网络连接出错:',err);
        }
    }

    /**
     * 响应服务端消息 type-->消息类型   data-->数据
     */
    public responseServerMessage(type,data) {
        console.log('服务端发消息->消息类型：',type,' 数据:',data);
        globalThis._eventTarget.emit(type,data);
    }

    private _sendMessage(_type,_data){
        let sendData = {
            type:_type,
            data:_data
        }
        this._ws.send(JSON.stringify(sendData));
    }
}



